<template>
  <div class="addTripPeople">
    <van-nav-bar
      class="header"
      :fixed="true"
      left-arrow
      title="新增出行人"
      :border="false"
      @click-left="onBack"
    >
    </van-nav-bar>
    <div class="people-wrapper">
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field
            v-model="state.form_data.cn_name"
            name="中文姓名"
            label="中文姓名"
            placeholder="与证件姓名一致"
            :required="true"
            input-align="right"
            error-message-align="right"
            :rules="[{ validator: validate.validateCnName }]"
          />
          <van-field
            v-model="state.form_data.en_name_first"
            name="英文姓 Surname"
            label="英文姓 Surname"
            placeholder="如张三丰填写为“ZHANG”"
            input-align="right"
            error-message-align="right"
            label-width="115"
            :required="state.is_required"
            :rules="
              state.is_required
                ? [{ validator: validate.validateEnFirstName }]
                : []
            "
          />
          <van-field
            v-model="state.form_data.en_name_end"
            name="英文名 Given name"
            label="英文名 Given name"
            placeholder="如张三丰填写为“SANFENG”"
            input-align="right"
            error-message-align="right"
            label-width="135"
            :required="state.is_required"
            :rules="
              state.is_required
                ? [{ validator: validate.validateEnEndName }]
                : []
            "
          />
          <div
            class="van-cell d-flex align-items-center"
            style="padding: 0;"
            v-for="(item, index) in state.form_data
              .common_passenger_certificates"
            :key="index"
          >
            <img
              src="../img/del.png"
              class="trip-del"
              @click="delTripPeople(index)"
              v-show="state.form_data.common_passenger_certificates.length > 1"
            />
            <div style="width:100%">
              <van-field
                v-model="item.certification_type"
                required
                readonly
                name="picker"
                label="证件类型"
                placeholder="请选择证件类型"
                input-align="right"
                error-message-align="right"
                @click="
                  (state.certification_type_showPicker = true),
                    (state.active_index = index),
                    watchCertificationType()
                "
                :rules="[{ required: true, message: '请选择证件类型' }]"
              />
              <van-popup
                v-model:show="state.certification_type_showPicker"
                position="bottom"
              >
                <van-picker
                  :columns="state.certification_type_list"
                  @confirm="getCertificationType"
                  @cancel="state.certification_type_showPicker = false"
                />
              </van-popup>
              <van-field
                v-model="item.certification_number"
                required
                name="证件号码"
                label="证件号码"
                placeholder="请输入证件号码"
                input-align="right"
                error-message-align="right"
                :rules="[{ validator: validate.validateIdNo }]"
                @blur="
                  handleNumberInputBlur(
                    item.certification_type,
                    item.certification_number
                  )
                "
              />
              <van-field
                v-model="item.certification_deadline"
                required
                readonly
                name="picker"
                label="证件有效期"
                placeholder="请选择证件有效期"
                input-align="right"
                error-message-align="right"
                @click="
                  (state.certification_deadline_showPicker = true),
                    (state.active_index = index)
                "
                :rules="[{ validator: validate.validateIdExpired }]"
              />
              <van-popup
                v-model:show="state.certification_deadline_showPicker"
                position="bottom"
              >
                <van-datetime-picker
                  type="date"
                  @confirm="getCertificationDeadline"
                  @cancel="state.certification_deadline_showPicker = false"
                />
              </van-popup>
              <van-field
                v-if="item.certification_type !== '身份证'"
                v-model="item.place_issue_name"
                readonly
                required
                clickable
                name="证件签发地"
                label="证件签发地"
                placeholder="请输入证件签发地"
                input-align="right"
                error-message-align="right"
                :rules="[{ validator: validate.validateIdIssuePlace }]"
                @click="goCheckCountry('place_issue_name', index)"
              />
            </div>
          </div>
          <div
            class="d-flex align-items-center justify-content-center"
            @click="addTripPeople"
          >
            <img src="../img/add.png" class="trip-add" />
            <div class="add-button">添加证件</div>
          </div>
          <van-field name="radio" label="性别" input-align="right">
            <template #input>
              <van-radio-group
                v-model="state.form_data.sex"
                direction="horizontal"
              >
                <van-radio name="1">男</van-radio>
                <van-radio name="0">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="state.form_data.country_cnname"
            :required="state.is_required"
            readonly
            clickable
            name="国籍"
            label="国籍"
            placeholder="请选择国籍"
            input-align="right"
            error-message-align="right"
            :rules="
              state.is_required
                ? [{ validator: validate.validateIdIssuePlace }]
                : []
            "
            @click="goCheckCountry('country_cnname')"
          />
          <van-field
            v-model="state.form_data.birthday"
            readonly
            name="picker"
            label="出生日期"
            placeholder="请选择出生日期"
            input-align="right"
            error-message-align="right"
            @click="state.birthday_showPicker = true"
          />
          <van-popup v-model:show="state.birthday_showPicker" position="bottom">
            <van-datetime-picker
              type="date"
              @confirm="getBirthday"
              @cancel="state.birthday_showPicker = false"
            />
          </van-popup>
          <van-field
            v-model="state.form_data.telephone"
            required
            name="手机号"
            label="手机号"
            placeholder="请输入手机号"
            input-align="right"
            error-message-align="right"
            :rules="[{ validator: validate.validateTelephone }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button native-type="submit" class="submit">
            确认
          </van-button>
        </div>
      </van-form>
    </div>
    <transition name="van-slide-right">
      <CheckCountry
        ref="CheckCountryRef"
        v-show="state.checkCountryShow"
        @checkCountryEmit="getCheckCountry"
        @checkCountryShow="getCheckCountryShow"
      />
    </transition>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import { reactive, getCurrentInstance, ref } from "vue";
import { Toast } from "vant";
import * as validate from "../../../assets/js/validate";
import { dateFormat } from "../../../assets/js/public";
import CheckCountry from "../CheckCountry/CheckCountry.vue";
const router = useRouter();
const { proxy } = getCurrentInstance();
const emit = defineEmits(["addSuccess"]);

const CheckCountryRef = ref(null);
const state = reactive({
  form_data: {
    cn_name: "", // 中文名
    en_name_first: "", // 英文姓
    en_name_end: "", // 英文名
    common_passenger_certificates: [
      {
        certification_type: "", // 证件类型
        certification_number: "", // 证件号
        certification_deadline: "", //有效期 yyyy-MM-dd
        place_issue: "", // 签发地二字码
        place_issue_name: "" // 签发地
      }
    ],
    sex: "1", // 性别
    country_cnname: "", // 国籍名称
    country_code: "", // 国籍二字码
    birthday: "", // 出生日期
    telephone: "", //手机号
    passenger_type: "ADT", // 乘客类型  ADT：成人，CHD：儿童
    out_reservation: "0"
  },
  // 证件类型 显示/隐藏
  certification_type_showPicker: false,
  // 证件有效期 显示/隐藏
  certification_deadline_showPicker: false,
  // 证件index
  active_index: null,
  // 签发地 国籍 显示/隐藏
  checkCountryShow: false,
  // 出生日期 显示/隐藏
  birthday_showPicker: false,
  // 如果证件类型有一个是护照 为true
  is_required: false,
  // 证件类型数组
  certification_type_list: [
    {
      text: "身份证",
      code: "00"
    },
    {
      text: "护照",
      code: "01"
    },
    {
      text: "军官证",
      code: "02"
    },
    {
      text: "士官证",
      code: "10"
    },
    {
      text: "回乡证",
      code: "03"
    },
    {
      text: "港澳通行证",
      code: "04"
    },
    {
      text: "台湾通行证",
      code: "05"
    },
    {
      text: "台胞证",
      code: "06"
    },
    {
      text: "海员证",
      code: "07"
    },
    {
      text: "其它",
      code: "09"
    }
  ]
});

// 获取出生日期
const getBirthday = val => {
  state.form_data.birthday = dateFormat(val, "yyyy-MM-dd");
  state.birthday_showPicker = false;
};

// 输入身份证号后  获取出生年月和性别
const handleNumberInputBlur = (type, number) => {
  if (type === "身份证" && number && number.length === 18) {
    let date = new Date(
      `${number.substring(6, 10)}-${number.substring(
        10,
        12
      )}-${number.substring(12, 14)}`
    );
    state.form_data.birthday = dateFormat(date, "yyyy-MM-dd");
    if (number[16] % 2 === 0) {
      state.form_data.sex = "0";
    } else {
      state.form_data.sex = "1";
    }
  }
};

const watchCertificationType = () => {
  let list = [
    {
      text: "身份证",
      code: "00"
    },
    {
      text: "护照",
      code: "01"
    },
    {
      text: "军官证",
      code: "02"
    },
    {
      text: "士官证",
      code: "10"
    },
    {
      text: "回乡证",
      code: "03"
    },
    {
      text: "港澳通行证",
      code: "04"
    },
    {
      text: "台湾通行证",
      code: "05"
    },
    {
      text: "台胞证",
      code: "06"
    },
    {
      text: "海员证",
      code: "07"
    },
    {
      text: "其它",
      code: "09"
    }
  ];
  state.form_data.common_passenger_certificates.forEach(v => {
    let index = list.findIndex(val => {
      return v.certification_type === val.text;
    });
    if (index > -1) {
      list.splice(index, 1);
    }
  });
  state.certification_type_list = list;
};

// 获取证件类型
const getCertificationType = val => {
  state.form_data.common_passenger_certificates[
    state.active_index
  ].certification_type = val.text;
  state.certification_type_showPicker = false;

  for (
    let i = 0;
    i < state.form_data.common_passenger_certificates.length;
    i++
  ) {
    if (
      state.form_data.common_passenger_certificates[i].certification_type ==
      "护照"
    ) {
      state.is_required = true;
      break;
    } else {
      state.is_required = false;
    }
  }
};

// 获取证件有效期
const getCertificationDeadline = val => {
  state.form_data.common_passenger_certificates[
    state.active_index
  ].certification_deadline = dateFormat(val, "yyyy-MM-dd");
  state.certification_deadline_showPicker = false;
};

// 点击证件签发地
const goCheckCountry = (type, index) => {
  // type判断从哪进入， index为赋值的下标
  state.checkCountryShow = true;
  CheckCountryRef.value.SetType(type);
  CheckCountryRef.value.SetIndex(index);
};

// 获取证件签发地的值
const getCheckCountry = params => {
  if (params.type == "place_issue_name") {
    state.form_data.common_passenger_certificates[params.index].place_issue =
      params.countryCode; // 签发地二字码
    state.form_data.common_passenger_certificates[
      params.index
    ].place_issue_name = params.countryCnname; // 签发地名称
  } else {
    state.form_data.country_code = params.countryCode; // 国籍二字码
    state.form_data.country_cnname = params.countryCnname; // 国籍名称
  }
};

// 证件签发地 子组件回调
const getCheckCountryShow = val => {
  state.checkCountryShow = val;
};

// 删除证件
const delTripPeople = index => {
  state.form_data.common_passenger_certificates.splice(index, 1);
};

// 添加证件
const addTripPeople = () => {
  let obj = {
    certification_type: "", // 证件类型
    certification_number: "", // 证件号
    certification_deadline: "", //有效期 yyyy-MM-dd
    place_issue: "", // 签发地二字码
    place_issue_name: "" // 签发地
  };
  state.form_data.common_passenger_certificates.push(obj);
};

// 提交
const onSubmit = async () => {
  let obj = JSON.parse(JSON.stringify(state.form_data));
  // 拿到证件类型的code
  obj.common_passenger_certificates.forEach(item => {
    state.certification_type_list.forEach(val => {
      if (item.certification_type == val.text) {
        item.certification_type = val.code;
      }
    });
  });
  const url = "/security/v1/commonPassenger/savePassenger";
  let params = {};
  let en_name = "";
  if (state.form_data.en_name_first && state.form_data.en_name_end) {
    en_name = state.form_data.en_name_first + "/" + state.form_data.en_name_end;
  }
  let save_common_passenger = {
    contact_member_id: localStorage.memberId, // 预定人memberId
    member_id: state.form_data.member_id || undefined, // 旅客memberId 组外人员没有
    cn_name: state.form_data.cn_name || undefined, // 出行人中文名
    en_name: en_name || undefined, // 出行人英文名
    telephone: state.form_data.telephone || undefined, // 出行人联系号码
    sex: state.form_data.sex || undefined, // 性别 0女   1男
    passenger_type: state.form_data.passenger_type || undefined, // 乘客类型  ADT：成人，CHD：儿童
    birthday: state.form_data.birthday || undefined, // 生日
    department_id: state.form_data.department_id || undefined, // 部门id
    department_name: state.form_data.department_name || undefined, // 部门名称
    cost_center_id: state.form_data.cost_center_id || undefined, // 成本中心Id
    cost_center_name: state.form_data.cost_center_name || undefined, // 成本中心名称
    country_code: state.form_data.country_code, // 国籍二字码
    country_cnname: state.form_data.country_cnname, // 国籍名称
    out_reservation: state.form_data.out_reservation, // 组外  0  组内 1
    common_passenger_certificates: obj.common_passenger_certificates //证件信息
  };
  params.save_common_passenger = save_common_passenger;

  let res = await proxy.$axiosJson(url, params);
  if (res.biz_result === "SUCCESS" && res.ret_code === "10000") {
    emit("addSuccess");
    onBack();
  } else {
    Toast(res.ret_msg || "请求失败，请检查网络。");
  }
};

const onBack = () => {
  router.back();
};
</script>

<style scoped lang="less">
.addTripPeople {
  :deep(.header) {
    position: static;
    box-shadow: 0px 0px 11px -3px rgba(0, 0, 0, 0.33);
    .van-icon {
      color: #000000;
    }
    .header-right {
      .sc(14px, #208cff);
      font-weight: 500;
    }
  }
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1100001;
  background: #f7f7f7;
  .people-wrapper {
    position: fixed;
    top: 45px;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 21;
    overflow-y: scroll;
    :deep(.van-form) {
      .van-cell-group {
        margin: 0;
        .van-field__label--required::before {
          margin-right: 0;
          color: var(--van-field-required-mark-color);
          content: "";
        }
        .van-field__label--required::after {
          margin-right: 0.05333rem;
          color: var(--van-field-required-mark-color);
          content: "*";
        }
      }
      .trip-del {
        width: 16px;
        height: 16px;
        padding: 10px 0 10px 10px;
      }
      .trip-add {
        width: 16px;
        height: 16px;
      }
      .add-button {
        color: #208cff;
        font-size: 16px;
        margin-left: 5px;
        padding: 20px 0;
      }
      .submit {
        background: #fe8f00;
        border-radius: 7px;
        width: 100%;
        font-size: 16px;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}
</style>
